import paramiko
import socket
import re, os, sys
from paramiko  import SSHClient
class PerfSSH(SSHClient):
    def __init__(self, server, port, username, password, timeout=5, **args):

        SSHClient.__init__(self)

        try:
            self.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 
            SSHClient.connect(self, server, port=port, username=username, password=password, timeout=timeout, **args) 
        except socket.error as ept:
            print 'soeckt error:' + str(ept)
            sys.exit(1)
        except paramiko.AuthenticationException as ept: 
            print 'auth error:' + str(ept)
            sys.exit(1)

        self.sftp = self.open_sftp()

    def recusive_put(self, localpath, remotepath):
        dirs = os.listdir(localpath) 
        try:
            self.sftp.mkdir(remotepath)
        except IOError:
            pass
        for dir in dirs:
            print dir
            if os.path.isdir(os.path.join(localpath, dir)):
                try:
                    self.sftp.mkdir(os.path.join(remotepath, dir))
                except IOError:
                    pass
                finally:
                    self.recusive_put(os.path.join(localpath, dir), os.path.join(remotepath, dir))
            else:
                self.sftp.put(os.path.join(localpath, dir), os.path.join(remotepath, dir))
    def chdir(self, dir):
        self.sftp.chdir(dir)
    def mkdir(self, dir):
        self.sftp.mkdir(dir)
    def getcwd(self):
        return self.sftp.getcwd()
    def listdir(self, path='.'):
        return self.sftp.listdir(path)
    def chmod(self, path, mode):
        self.sftp.chmod(path, mode)

    def put(self, localpath, remotepath):
        self.sftp.put(localpath, remotepath)
    def get(self, remotepath, localpath):
        self.sftp.get(remotepath, localpath)

    def remove(self, path):
        self.sftp.remove(path)
    
    def exec_command(self, cmd, show=False):
        stdin, stdout, stderr = SSHClient.exec_command(self, cmd) 
        temp = stdout.readlines()
        if show:
            for std in temp:
                print std,
            for std in stderr.readlines():
                print std,
        return temp

    def get_server_cpus(self):
        result = self.exec_command('cat /proc/cpuinfo | grep "processor" | sort | uniq|wc -l')
        cpus = int(result[0].strip('\n'))

        return cpus
    
    def close(self):
        self.sftp.close()
        SSHClient.close(self) 

if __name__ == '__main__':
    localpath=os.getcwd()
    remotepath="/root/just_test"
    sshclient = PerfSSH(server='202.173.9.17', port=22, username="root", password='zdns@knet.cn', timeout=3) 
    #sshclient.exec_command('ls -l', True)
    print sshclient.getcwd()
    print sshclient.listdir()
    #sshclient.recusive_put(localpath, remotepath)
    #sshclient.put(localpath + '/bind.tar.gz', remotepath + '/bind.tar.gz')
    sshclient.close()
